package jsyf.oa.service.wechat.service_account;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.oa.facade.wechat.config.WeChatConst;
import jsyf.oa.facade.wechat.service_account.WechatCustomServiceFacade;
import jsyf.oa.facade.wechat.service_company.TokenFacade;
import jsyf.oa.service.wechat.service_company.HttpUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class WechatCustomServiceService implements WechatCustomServiceFacade {

    @Resource
    private TokenFacade tokenFacade;

    @Override
    public JSONObject addCustomservice(String jsonData) {

        // 数据库中获取access_token
        String accessToken = tokenFacade.getServiceAccessToken(WeChatConst.weChat_account_type);
        // 拼装创建模板消息所属行业的url
        String url = WeChatConst.add_customservice.replace("ACCESS_TOKEN",accessToken);
        // 调用接口查询模板id
        JSONObject jsonObject = HttpUtil.request(url, "POST", jsonData);

        return jsonObject;
    }

    @Override
    public JSONObject getCustomservice() {

        // 数据库中获取access_token
        String accessToken = tokenFacade.getServiceAccessToken(WeChatConst.weChat_account_type);
        // 拼装创建模板消息所属行业的url
        String url = WeChatConst.get_customservice.replace("ACCESS_TOKEN",accessToken);
        // 调用接口查询模板id
        JSONObject jsonObject = HttpUtil.request(url, "GET", null);

        return jsonObject;
    }

    @Override
    public JSONObject sendMessage(String jsonData) {

        JSONObject obj = JSON.parseObject(jsonData);
        String touser = obj.getString("touser");
        String content = obj.getString("content");

        // 数据库中获取access_token
        String accessToken = tokenFacade.getServiceAccessToken(WeChatConst.weChat_account_type);
        // 拼装创建模板消息所属行业的url
        String url = WeChatConst.sendmessage_customservice.replace("ACCESS_TOKEN",accessToken);
        JSONObject paramJsonObject = new JSONObject();
        paramJsonObject.put("touser", touser);
        paramJsonObject.put("msgtype", "text");
        JSONObject contentObj = new JSONObject();
        contentObj.put("content", content);
        paramJsonObject.put("text", contentObj);
        // 调用接口查询模板id
        JSONObject jsonObject = HttpUtil.request(url, "POST", paramJsonObject.toJSONString());

        return jsonObject;
    }
}
